<template>
  <div id="app">
    <my-header>{{ headerTitle }}</my-header>
    <router-view />
  </div>
</template>

<script>
import MyHeader from "./components/Header/index.vue";

import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { computed, watch } from "vue";

export default {
  name: "App",
  components: {
    MyHeader,
  },
  setup() {
    const router = useRouter(),
      store = useStore(),
      state = store.state;

    //当app挂载时先回到首页
    router.push("/");

    //监听路由变化
    watch(
      () => {
        return router.currentRoute.value.name;
      },
      (value) => {
        store.commit("setHeaderTitle", value);
      }
    );

    return {
      //注意：在vue2.x中是通过computed里 ...mapState(['xxx'])方法拿到里面的属性
      //1.所以这里不能直接访问state.headerTitle
      //2.所以需要用computed函数取出state里的属性
      headerTitle: computed(() => state.headerTitle),
    };
  },
};
</script>